class UsersController < ApplicationController
  before_filter :find_user,           :only => [:show,  :edit,    :update,  :destroy]
  before_filter :find_list_items,     :only => [:show,  :new,     :update,  :create,  :edit]
  before_filter :require_login,       :only => [:edit,  :update]
  before_filter :already_logged_in?,  :only => [:new,   :create]
  before_filter :require_admin,       :only => [:destroy]

  def index
    @users = User.find(:all, :order => 'created_at DESC')
  end

  def show
  end

  def new
    session[:return_to] = request.referer
    @user = User.new
  end

  def create
    cookies.delete :auth_token
    @user = User.new(params[:user])
    @user.save
    if @user.errors.empty?
      self.current_user = @user
      redirect_back_or_default('/')
      flash[:update] = "Thanks for signing up!"
    else
      render :action => 'new'
    end
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'new'
  end

  def edit
  end

  def update
    @user.update_attributes!(params)
    flash[:update] = 'The user information has been updated.'
    redirect_to user_url(@user)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'edit'
  end

  def destroy
    @user.destroy
    flash[:update] = 'The user has been deleted.'
    redirect_to users_url
  end

protected
  def already_logged_in?
    if logged_in? && !current_user.is_admin?
      flash[:update] = "You are already logged in."
      redirect_to :back
    end
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def require_admin
    if logged_in?
      unless current_user.is_admin?
        flash[:error] = "Must be an administrator to do that, sorry."
        redirect_back_or_default('/')
      end
    else
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def find_user
    @user = User.find params[:id]
  end
  def find_list_items
    @videos   = Video.find    :all, :order => 'created_at desc'
    @albums   = Album.find    :all, :order => 'created_at desc'
    @artwork  = Artwork.find  :all, :order => 'created_at desc', :conditions => ["thumbnail IS ?", nil]
    @photos   = Photo.find    :all, :order => 'created_at desc', :conditions => ["thumbnail IS ?", nil]
    @shows    = Show.find     :all, :order => 'created_at desc'
    @songs    = Song.find     :all, :order => 'created_at desc'
  end
end
